import { useState } from 'react';
import type { FC } from 'react';
import { Upload, Button, Typography, Space, message } from 'antd';
import type { UploadFile, UploadChangeParam } from 'antd/lib/upload/interface';
import { getToken } from '@/utils/auth';

interface ProFormUploadFileProps {
  value?: string;
  onChange?: (val: string) => void;

  uploadType?: string;
  buttonText?: string;

  responseKey: string;
  onDownloadTemplate?: () => void;
}

const UploadFileGetUrl: FC<ProFormUploadFileProps> = ({
  value,
  onChange,
  uploadType,
  buttonText,
  responseKey,
  onDownloadTemplate,
}) => {
  const [loading, setLoading] = useState<boolean>(false);

  function handleChange({ file }: UploadChangeParam<UploadFile<any>>) {
    if (file.status === 'done') {
      setLoading(false);
      onChange?.(file.response.data[responseKey] as string);
    } else if (file.status === 'error') {
      message.error('上传失败');
      setLoading(false);
    } else {
      setLoading(true);
    }
  }

  return (
    <div>
      <Space>
        <Upload
          action={`/api/cos/uploadFile?type=${uploadType}`}
          headers={{ Authorization: getToken() }}
          multiple={false}
          withCredentials={true}
          onChange={handleChange}
        >
          <Button type="primary" loading={loading}>
            {buttonText || '上传文件'}
          </Button>
        </Upload>
        {onDownloadTemplate && (
          <Button type="link" onClick={onDownloadTemplate}>
            下载模板
          </Button>
        )}
      </Space>
      {value && (
        <Typography.Paragraph ellipsis={{ rows: 1, expandable: true }} style={{ marginTop: 5 }}>
          {value}
        </Typography.Paragraph>
      )}
    </div>
  );
};

export default UploadFileGetUrl;
